package com.madarasan.providers;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.madarasan.SkiDroid.MyApplication;
import com.madarasan.SkiDroid.R;
import com.madarasan.weather.ShowResortWeather;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ShowProviderList extends ListActivity {

	String title;
	DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
	ArrayList<ArrayList<String>> providers = new ArrayList<ArrayList<String>>();
	String path = "http://dragos.madarasan.com/ski/providers.xml";
	Integer results = 0;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		Log.i("ShowProviderList", "onCreate called");

		title = ((MyApplication) this.getApplication()).getTitle();

		new DownloadFilesTask().execute();

	}

	private class DownloadFilesTask extends AsyncTask<Void, Integer, Integer> {

		public ProgressDialog dialog;

		@Override
		protected void onPreExecute() {

			dialog = new ProgressDialog(ShowProviderList.this);
			dialog.setCancelable(false);
			dialog.setMessage(getApplicationContext().getResources().getString(R.string.dialog_loading));
			dialog.setMax(100);
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.show();
			// Log.d("ShowResortList->onPreExecute","shown diag");

		}

		@Override
		protected Integer doInBackground(Void... unused) {

			Log.i("ShowProviderList", "reading feed");

			// Integer results = 0;

			try {

				domFactory.setNamespaceAware(true);
				DocumentBuilder builder = domFactory.newDocumentBuilder();
				XPath xpath = XPathFactory.newInstance().newXPath();

				Log.i("ShowProviderList", "Checking before parse");
				Document doc = builder.parse(path);
				Log.i("ShowProviderList", "Checking after parse");

				XPathExpression expr = xpath.compile("/providers/center[resort='"
						+ title.toLowerCase().replaceAll(" ", "") + "']");

				Log.i("ShowProviderList", "Checking before evaluation");
				NodeList nodes = (NodeList) expr.evaluate(doc,
						XPathConstants.NODESET);
				Log.i("ShowProviderList", "Checking after evaluation");

				for (Integer i = 0; i < nodes.getLength(); i++) {
					results = nodes.getLength();

					NodeList items = nodes.item(i).getChildNodes();
					ArrayList<String> provider = new ArrayList<String>();

					provider.add(items.item(3).getTextContent()); // add the
																	// names to
																	// titles
																	// array
					provider.add(items.item(5).getTextContent()); // add the
																	// address
																	// to titles
																	// array
					provider.add(items.item(7).getTextContent()); // add the
																	// telephone
																	// to titles
																	// array
					provider.add(items.item(9).getTextContent()); // add the
																	// latitude
																	// to titles
																	// array
					provider.add(items.item(11).getTextContent()); // add the
																	// longitude
																	// to titles
																	// array
					provider.add(items.item(13).getTextContent()); // add the
																	// boots to
																	// titles
																	// array
					provider.add(items.item(15).getTextContent()); // add the
																	// skies to
																	// titles
																	// array
					provider.add(items.item(17).getTextContent()); // add the
																	// sticks to
																	// titles
																	// array
					providers.add(provider);

					publishProgress((int) ((i / (float) results) * 100));

				}

			}

			catch (Exception e) {
				e.printStackTrace();
			}

			Log.i("ShowProviderList", "exiting doInBackground");
			return 1;

		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// Log.i("ShowResortList", "updating progress to "+values[0]);
			dialog.setProgress((int) values[0]);

		};

		@Override
		protected void onPostExecute(Integer result) {
			// Log.i("ShowResortList onPostExecute",
			// " hiding dialog, calling loadFeed");
			dialog.hide();

			loadFeed();

		}

	}

	public void loadFeed() {

		if (results == 0) {
			Toast.makeText(getApplicationContext(),
					getApplicationContext().getResources().getString(R.string.providerlist_noresults), Toast.LENGTH_LONG).show();
			Intent ShowResortWeather = new Intent(this, ShowResortWeather.class);
			startActivity(ShowResortWeather);
		}

		try {

			List<String> providerNames = new ArrayList<String>();
			for (Integer i = 0; i < providers.size(); i++) {

				providerNames.add(providers.get(i).get(0).toString());
			}

			setContentView(R.layout.providers);

			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					R.layout.row, providerNames);
			this.setListAdapter(adapter);

			final ListView lv = getListView();
			lv.setItemsCanFocus(false);
			lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		} catch (Throwable t) {
			Log.e("ShowProviderList", t.getMessage(), t);
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		Intent ShowProviderInfo = new Intent(this, ShowProviderInfo.class);

		// Log.e("First",providers.get(position).get(0).toString());

		ShowProviderInfo.putExtra("name", providers.get(position).get(0)
				.toString());
		ShowProviderInfo.putExtra("address", providers.get(position).get(1)
				.toString());
		ShowProviderInfo.putExtra("telephone", providers.get(position).get(2)
				.toString());
		ShowProviderInfo.putExtra("latitude", providers.get(position).get(3)
				.toString());
		ShowProviderInfo.putExtra("longitude", providers.get(position).get(4)
				.toString());
		ShowProviderInfo.putExtra("boots", providers.get(position).get(5)
				.toString());
		ShowProviderInfo.putExtra("skies", providers.get(position).get(6)
				.toString());
		ShowProviderInfo.putExtra("sticks", providers.get(position).get(7)
				.toString());

		startActivity(ShowProviderInfo);

	}

}
